package Server.Model.Hall;

import java.util.Map;

import Server.Agent.GameAgent;
import common.routine.RedisUtil;
import net.sf.json.JSONObject;
import redis.clients.jedis.Jedis;
import redis.protocal.DbInfoMgr;

public class WxGameMgr {
	private static WxGameMgr _instance = null;
	private static final String WXGAME_RANK_TIME = "wxgame_rank_time";
	private static final String WXGAME_RANK_DATA = "wxgame_rank_data";
	public static WxGameMgr getInstance(){
		if(_instance == null){
			_instance = new WxGameMgr();
			_instance.init();
		}
		return _instance;
	}
	private void init(){
		
	}
	public boolean OnRecv(GameAgent agent,JSONObject root){
		String command = root.optString("command");
		String game = root.optString("gameType");
		
		switch(command){
		case "hall_get_gamerank":{
			String key = WXGAME_RANK_DATA + game;
			Jedis jedis = RedisUtil.getJedis();
			String ranktimestr = jedis.hget(WXGAME_RANK_TIME,game);
			int ranktime = 0;
			if(ranktimestr != null){
				ranktime = Integer.parseInt(ranktimestr);
			}
			int currtime = (int) (System.currentTimeMillis() / 1000);
			if(currtime - ranktime > 3600){
				//一个小时排序一次
				Map<String,String> alls = DbInfoMgr.getInstance().getOtherGameAllUserData(game);
				//一般就是分数，等级，金币,局数(score,level,gold,round)
				SimpleRankUtil ranktool = SimpleRankUtil.getInstance();
				JSONObject[] scorerank = ranktool.quickSortTop100(alls, "score", 100);
				JSONObject[] levelrank = ranktool.quickSortTop100(alls, "level", 5);
				JSONObject[] goldrank = ranktool.quickSortTop100(alls, "gold", 10000);
				JSONObject[] roundrank = ranktool.quickSortTop100(alls, "round", 20);
				//存储
				jedis.ltrim(key + "score", 0, -1);//清空score
				for(int i = 0;i < 100 && i < scorerank.length && scorerank[i] != null;i++){
					jedis.rpush(key + "score", scorerank[i].toString());
				}
				jedis.ltrim(key + "level", 0, -1);//清空level
				for(int i = 0;i < 100 && i < levelrank.length && levelrank[i] != null;i++){
					jedis.rpush(key + "level", levelrank[i].toString());
				}
				jedis.ltrim(key + "gold", 0, -1);//清空gold
				for(int i = 0;i < 100 && i < goldrank.length && goldrank[i] != null;i++){
					jedis.rpush(key + "gold", goldrank[i].toString());
				}
				jedis.ltrim(key + "round", 0, -1);//清空round
				for(int i = 0;i < 100 && i < roundrank.length && roundrank[i] != null;i++){
					jedis.rpush(key + "round", roundrank[i].toString());
				}
			}
			//取数据
			//score
			//level
			//gold
			//score
			//发送数据
			
			RedisUtil.returnResource(jedis);
			break;
		}
		}
		return true;
	}
}
